package com.tcxhb.job.core.service.impl;

import com.tcxhb.job.common.model.MiscResult;
import com.tcxhb.job.core.service.ShellService;
import org.apache.commons.lang3.SystemUtils;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description:
 * @Auther: tcxhb
 * @Date: 2023/11/21
 */
@Component
public class ShellServiceImpl implements ShellService {
    @Override
    public MiscResult<List<String>> command(String command) {
        List<String> commands = new ArrayList<>();
        if (SystemUtils.IS_OS_WINDOWS) {
            // Windows
            commands.add("cmd");
            commands.add("/c");
        } else {
            // Unix/Linux/MacOS
            commands.add("/bin/sh");
            commands.add("-c");
        }
        commands.add(command);
        List<String> list = process(commands);
        return MiscResult.suc(list);
    }

    /**
     * 执行shell脚本
     * @param commands
     * @return
     */
    public List<String> process(List<String> commands) {
        try {
            Charset charset = System.getProperty("os.name").toLowerCase().contains("win") ? Charset.forName("GBK") : Charset.defaultCharset();
            ProcessBuilder processBuilder = new ProcessBuilder(commands);
            Process process = processBuilder.start();
            // 获取输出
            List<String> output = readStream(process.getInputStream(), charset);
            // 等待进程结束
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                return output;
            }
            return readStream(process.getErrorStream(), charset);
        } catch (IOException | InterruptedException e) {
            Thread.currentThread().interrupt();
            return Arrays.asList(e.getMessage());
        }
    }
    public List<String> readStream(InputStream inputStream, Charset charset) {
        List<String> result = new ArrayList<>();
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, charset));
            String line;
            while ((line = reader.readLine()) != null) {
                result.add(line);
            }
        } catch (Exception e) {
        }
        return result;
    }

    public static void main(String []args){
        ShellServiceImpl service = new ShellServiceImpl();
        MiscResult<List<String>>  result = service.command("ping www.baidu.com");
        System.out.print(result);
    }
}
